package db;



import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;

public class DBConnector {
	private static Session session = null;
	private static Transaction transaction = null;
	@Autowired
	private static SessionFactory sessionFactory;
	private DBConnector() {
		//Singleton
	}
	
	public static Session getInstance(){
		if(session == null){
			init();
		}
		return session;
	}
	private static void init(){
		try{
//			SessionFactory sf = new Configuration().configure().buildSessionFactory();
			SessionFactory sf = sessionFactory;
			session = sf.openSession();
			transaction = session.beginTransaction();
			
		}
		catch (Exception e) {
			e.printStackTrace();
			System.out.println("No connection to the DB. Exiting...");
			System.exit(0);
		}
	}
	public static void close(){
		transaction.commit();
		session.flush();
		session.close();
		System.out.println("Hibernate Session closed");
		session = null;
	}
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		session.flush();
		session.close();
		System.out.println("Hibernate Session closed by finalizer");
	}
	
}

